﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HanumanInstitute.MvvmDialogs;
using System.Collections.ObjectModel;
using System.IO;
using TS2MP4.Models;
using TS2MP4.Services;
using Xabe.FFmpeg;

namespace TS2MP4.ViewModels;

internal partial class MainViewModel(IDialogService dialogService, IOpenExplorerService openExplorerService) : ObservableObject
{
    [ObservableProperty]
    private string? _inPath;

    [ObservableProperty]
    private int _finishedCount;

    [ObservableProperty]
    private bool _isDeleteFiles;

    [ObservableProperty]
    private bool _isOpenExplorerWhenFinished;

    public ObservableCollection<TsFile> TsFiles { get; } = [];

    [RelayCommand]
    private async Task Browse()
    {
        using var folder = await dialogService.ShowOpenFolderDialogAsync(this);
        if (folder != null)
        {
            InPath = folder.LocalPath;

            if (TsFiles.Any())
            {
                TsFiles.Clear();
            }

            foreach (var file in Directory.GetFiles(InPath, "*.ts"))
            {
                TsFiles.Add(new TsFile(await FFmpeg.GetMediaInfo(file)));
            }
        }
    }

    [RelayCommand]
    private async Task Refresh()
    {
        if (Directory.Exists(InPath))
        {
            if (TsFiles.Any())
            {
                TsFiles.Clear();
            }

            foreach (var file in Directory.GetFiles(InPath, "*.ts"))
            {
                TsFiles.Add(new TsFile(await FFmpeg.GetMediaInfo(file)));
            }
        }
    }

    [RelayCommand]
    private async Task Convert()
    {
        var isDeleteFiles = IsDeleteFiles;
        var isOpenExplorerWhenFinished = IsOpenExplorerWhenFinished;
        FinishedCount = 0;
        foreach (var tsFile in TsFiles)
        {
            tsFile.Result = await Convert(tsFile) ? Result.Success : Result.Failure;
            if (tsFile.Result == Result.Success && isDeleteFiles)
            {
                File.Delete(tsFile.MediaInfo.Path);
            }
            FinishedCount++;
        }
        if (TsFiles.Any() && Directory.Exists(InPath) && isOpenExplorerWhenFinished)
        {
            openExplorerService.OpenExplorer(InPath);
        }
    }

    private static async Task<bool> Convert(TsFile tsFile)
    {
        try
        {
            var mediaInfo = tsFile.MediaInfo;
            var videoStream = mediaInfo.VideoStreams.First().SetCodec(VideoCodec.copy);
            var audioStream = mediaInfo.AudioStreams.First().SetCodec(AudioCodec.copy);
            await FFmpeg.Conversions.New()
                .AddStream<IStream>(videoStream, audioStream)
                .SetOutput(Path.ChangeExtension(mediaInfo.Path, ".mp4"))
                .Start();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}